package qimao.com.edu.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import qimao.com.edu.DTO.BookDTO;
import qimao.com.edu.DTO.WorkQueryDTO;
import qimao.com.edu.entity.CommenResult;
import qimao.com.edu.entity.Page;
import qimao.com.edu.service.WorksService;
import qimao.com.edu.service.impl.WorksServiceImpl;



@WebServlet("/selectBookByConditions.do")
public class selectBookByConditions extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		
		WorksService ws = new WorksServiceImpl();
		int pageNum = 1;
		int pageSize = 10;
		
		WorkQueryDTO wd = new WorkQueryDTO();
		Page page = null;
		
		// 读取请求体中的JSON数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String json = sb.toString();
		
		try {
            System.out.println(1);
			// 使用Jackson将JSON转换为WorkQueryDTO对象
            ObjectMapper mapper = new ObjectMapper();
			wd = mapper.readValue(json, WorkQueryDTO.class);
            System.out.println(2);
			
			// 从DTO中获取分页信息
			if (wd.getPageNum() != null && wd.getPageNum() > 0) {
                pageNum = wd.getPageNum();
                System.out.println(pageNum);
            }
            if (wd.getPageSize() != null && wd.getPageSize() > 0) {
                pageSize = wd.getPageSize();
            }
            
            page = ws.searchWorks(wd, pageNum, pageSize);
		} catch (Exception e) {
			e.printStackTrace(); // 打印异常堆栈信息
		    System.err.println("JSON解析失败: " + e.getMessage());
		}
	    
	    
	    CommenResult cr = new CommenResult();
		cr.setCode(200);
		cr.setMsg("success");
		cr.setData(page);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(cr.toJsonString());
		
	}
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
}
